"use strict";
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.wxLogin = exports.fetch = exports.buttonClicked = exports.BASE_URL = exports.formatTimeMills = exports.formatTime = exports.formatDateStr = void 0;
// 日期格式化
/**
* 格式化时间
* 调用formatDate(strDate, 'yyyy-MM-dd');
* @param strDate（中国标准时间、时间戳等）
* @param strFormat（返回格式）
*/
var formatDateStr = function (strDate, strFormat) {
    if (!strDate) {
        return;
    }
    if (!strFormat) {
        strFormat = 'yyyy-MM-dd HH:mm:ss';
    }
    switch (typeof strDate) {
        case 'string':
            strDate = new Date(strDate.replace(/-/, '/'));
            break;
        case 'number':
            strDate = new Date(strDate);
            break;
    }
    if (strDate instanceof Date) {
        var dict_1 = {
            yyyy: strDate.getFullYear(),
            M: strDate.getMonth() + 1,
            d: strDate.getDate(),
            H: strDate.getHours(),
            m: strDate.getMinutes(),
            s: strDate.getSeconds(),
            MM: ('' + (strDate.getMonth() + 101)).substr(1),
            dd: ('' + (strDate.getDate() + 100)).substr(1),
            HH: ('' + (strDate.getHours() + 100)).substr(1),
            mm: ('' + (strDate.getMinutes() + 100)).substr(1),
            ss: ('' + (strDate.getSeconds() + 100)).substr(1),
        };
        return strFormat.replace(/(yyyy|MM?|dd?|HH?|mm?|ss?)/g, function () {
            return dict_1[arguments[0]];
        });
    }
};
exports.formatDateStr = formatDateStr;
var formatTime = function (date) {
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var day = date.getDate();
    var hour = date.getHours();
    var minute = date.getMinutes();
    var second = date.getSeconds();
    return ([year, month, day].map(formatNumber).join('-') +
        ' ' +
        [hour, minute, second].map(formatNumber).join(':'));
};
exports.formatTime = formatTime;
var formatTimeMills = function (date) {
    var year = date.getTime();
    var month = date.getMonth() + 1;
    var day = date.getDate();
    // return (
    //   [year, month, day].map(formatNumber).join('/') +
    //   ' ' +
    //   [hour, minute, second].map(formatNumber).join(':')
    // )
    return ([year, month, day].map(formatNumber).join('-'));
};
exports.formatTimeMills = formatTimeMills;
// 数字格式化
var formatNumber = function (n) {
    var s = n.toString();
    return s[1] ? s : '0' + s;
};
// URL参数处理
var getQueryString = function (params) {
    var paramStrings = [];
    for (var key in params) {
        paramStrings.push(key + '=' + params[key]);
    }
    return paramStrings.length > 0 ? '?' + paramStrings.join('&') : '';
};
// Base URL (注意：不要以 / 结尾)
exports.BASE_URL = "http://192.168.1.106:8085";
//export const BASE_URL = "https://gl.tsrlsf.com:13180";
var buttonClicked = function (self) {
    self.setData({
        buttonClicked: true
    });
    setTimeout(function () {
        self.setData({
            buttonClicked: false
        });
    }, 1500);
};
exports.buttonClicked = buttonClicked;
// 发送请求
var fetch = function (option) {
    return new Promise(function (resolve, reject) {
        // URL 处理
        var url = option.url || '';
        option.url = (url.indexOf('http://') != -1 || url.indexOf('https://') != -1) ? url : exports.BASE_URL + url;
        // 处理 QueryString
        if (option.params) {
            var queryString = getQueryString(option.params);
            option.url = option.url + queryString;
        }
        // 请求头
        var headers = option.headers || {};
        var token = wx.getStorageSync('SYS_TOKEN');
        // 填充 TOKEN
        if (!token) {
            wx.showToast({ title: '当前用户尚未登录', icon: 'none' });
            reject();
        }
        headers['Authorization'] = "Bearer " + token;
        option.header = headers; // 兼容性处理：umi request 的请求头参数是带s的（headers），小程序的是不带s的（header）
        // 发起请求
        wx.request(__assign(__assign({}, option), { success: function (res) {
                if (res.data.code === 10010) {
                    wx.showToast({
                        title: '用户凭证过期，请重新登录',
                        icon: "none"
                    });
                }
                // 同时兼容回调函数和 Promise 两种写法
                if (option.success) {
                    if (option.getReponse) {
                        option.success(res);
                    }
                    else {
                        option.success(res.data);
                    }
                }
                if (option.getReponse) {
                    resolve(res);
                }
                else {
                    resolve(res.data);
                }
            }, fail: function (err) {
                // 同时兼容回调函数和 Promise 两种写法
                if (option.fail) {
                    option.fail(err);
                }
                reject(err);
            } }));
    });
};
exports.fetch = fetch;
var wxLogin = function () {
    wx.qy.login({
        success: function (res) {
            console.log(res.code);
            // 发起登录请求
            wx.request({
                method: 'POST',
                url: exports.BASE_URL + '/api/login',
                data: {
                    weChatCode: res.code
                },
                success: function (res) {
                    var result = res && res.data;
                    wx.hideLoading();
                    if (result.code === 0) {
                        // 登录成功，暂存 TOKEN
                        wx.setStorageSync('SYS_TOKEN', result.data);
                        wx.showToast({
                            title: '登录成功',
                            icon: 'none'
                        });
                    }
                    else if (result.code === 10013) {
                        wx.showToast({
                            icon: "none",
                            title: result.msg
                        });
                        wx.navigateTo({
                            url: '/pages/report/detail/reportDetail'
                        });
                    }
                    else {
                        wx.showToast({
                            title: "\u767B\u5F55\u5931\u8D25 [" + result.code + "] " + result.msg,
                            icon: 'none'
                        });
                    }
                },
                fail: function (err) {
                    console.error('登录失败 [2]', err);
                    wx.hideLoading();
                    wx.showToast({
                        title: '登录失败 [2] 网络异常',
                        icon: 'none'
                    });
                }
            });
            // 发送 res.code 到后台换取 openId, sessionKey, unionId
        },
    });
};
exports.wxLogin = wxLogin;
